package com.xing.crm.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.xing.crm.utils.UploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Mr.L
 * @version V1.0
 * @date 2021年07月21日 17:37
 */
@RestController
public class UploadController
{

	@Autowired
	UploadUtils UploadUtils;
	private Logger log = LoggerFactory.getLogger(getClass().getName());
	@RequestMapping({"/upload"})
	public Map<String, Object> upload(HttpServletRequest request, MultipartFile[] files) {
		String type = request.getParameter("type");
		Map result = new HashMap(0);
		result.put("code", Integer.valueOf(0));
		result.put("msg", "上传成功");
		List<String> fileNames = null;
		String savePath = "/upload/";
		try {
			if (type.equalsIgnoreCase("") || type == null) {
				log.info("图片上传，type错误：{} {}", type, request.getRequestURI());
				type = "";
			}

			switch (type) {
				case "category":
					fileNames = UploadUtils.saveFile(request, files, savePath + "category/");
					break;
				case "products":
					fileNames = UploadUtils.saveFile(request, files, savePath + "product/");
					break;
				default:
					fileNames = UploadUtils.saveFile(request, files, savePath + "others/");
					break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("msg", "上传失败");
			result.put("code", -1);
		}
		result.put("data", fileNames);

		return result;
	}
}
